package com.msh.starter.common.web.config;

import com.msh.frame.client.interfaces.IClassLoadLog;
import com.msh.starter.common.web.bean.JsLongAccuracySerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * 对于返回对象的处理 把long类型全部转换为字符串 防止精度丢失
 */
@ConditionalOnProperty(name = "msh.starter.web.jackson.enable", havingValue = "true", matchIfMissing = true)
public class JacksonConfig implements IClassLoadLog {

  @Bean("jackson2ObjectMapperBuilderCustomizer")
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    Jackson2ObjectMapperBuilderCustomizer customizer = new Jackson2ObjectMapperBuilderCustomizer() {
      @Override
      public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        jacksonObjectMapperBuilder.serializerByType(Long.class, JsLongAccuracySerializer.instance)
            .serializerByType(Long.TYPE, JsLongAccuracySerializer.instance);
      }
    };
    return customizer;
  }


  @Override
  public String logInfo() {
    return new StringBuilder()
        .append("----执行类 ")
        .append(JacksonConfig.class)
        .append("\r\n")
        .append("--------加载类 ")
        .append(Jackson2ObjectMapperBuilderCustomizer.class)
        .append("\r\n")
        .toString();
  }
}
